#include "ClientSocket.h"
#include <QByteArray>

ClientSocket::ClientSocket(const SocketSettings& settings, const QString& name)
: _settings(settings)
, _socket(new QTcpSocket)
{ 
    connect(_socket.get(), SIGNAL(disconnected()), this, SIGNAL(disconnected()));
    connect(_socket.get(), SIGNAL(readyRead()), this, SLOT(HasData()), Qt::DirectConnection);
}

bool ClientSocket::Open()
{
    Reset();
    _socket->connectToHost(_settings.host, _settings.port);        

    return (QHostAddress(_settings.host) == QHostAddress::LocalHost) ? _socket->isOpen() : _socket->waitForConnected(_settings.timeout);  
}

bool ClientSocket::IsOpened()
{
    return _socket->isValid() && (_socket->state() == QAbstractSocket::ConnectedState);
}

void ClientSocket::Reset()
{
    _socket->abort();
}

void ClientSocket::Close()
{   
    Reset();
    _socket->close();
}

unsigned ClientSocket::DataAvailable()
{
    return _socket->bytesAvailable();
}

QString ClientSocket::LastError()
{
    return _socket->errorString();
}

QString ClientSocket::Info()
{
    return QString("Client TCP socket to %2@%1.").arg(_settings.host, QString("%1").arg(_settings.port));
}

QByteArray ClientSocket::Receive(unsigned size)
{
    return _socket->read(size);
}

unsigned ClientSocket::Send(const QByteArray& data)
{
    unsigned bytes = _socket->write(data);
    _socket->flush();
    
    return bytes;
}